package com.bitrate.dagger.server.websocket.controller;

import java.util.concurrent.CopyOnWriteArrayList;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.bitrate.dagger.restful.response.ResponseResult;
import com.bitrate.dagger.server.websocket.auth.Transmitter;
import com.bitrate.dagger.server.websocket.cache.LocalCache;

import cn.hutool.core.util.StrUtil;

/**
 * 鉴权相关Controller
 */
@RestController
@RequestMapping("/auth")
public class TransmitterController {

	/**
	 * 获取oAuth鉴权Token
	 */
	@GetMapping("authorize/{seed}")
	public ResponseResult<String> authorize(@PathVariable(name = "seed") String seed) {
		if (StrUtil.isEmpty(seed)) {
			return ResponseResult.failNotice("授信Seed缺失");
		}
		// 判断种子来源合法性
		Boolean verify = false;
		CopyOnWriteArrayList<String> commonKeyArr = LocalCache.dataList;
		for (String commonKey : commonKeyArr) {
			Integer length = commonKey.length();
			String verifySeed = StrUtil.sub(commonKey, length >> 2, length >> 1);
			if (verifySeed.equals(seed)) {
				verify = true;
			}
		}
		if (!verify) {
			return ResponseResult.failNotice("授信Seed错误");
		}
		String authToken = Transmitter.genToken(seed);
		return ResponseResult.success(authToken);
	}

	public static void main(String[] args) {
		String commonKey = "6cff468a9bee666d21a144b35236b06c";
		Integer length = commonKey.length();
		String seed = StrUtil.sub(commonKey, length >> 2, length >> 1);
		System.out.println(seed);
		System.out.println(Transmitter.genToken(seed));
	}

}
